package com.mall.common.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import org.springframework.orm.jpa.SharedEntityManagerCreator;

public class EntityManagerHelper {

	private static final Logger logger;
	private static EntityManager entityManager;
	static{
		logger = Logger.getLogger("entityManagerFactory");
	}

	public static void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		entityManager = SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
	}

	public static EntityManager getEntityManager(){
		return entityManager;
	}

	public static void closeEntityManager(){
		getEntityManager().close();
	}
	
	public static void beginTransaction(){
		getEntityManager().getTransaction().begin();
	}
	
	public static void commit(){
		getEntityManager().getTransaction().commit();
	}
	
	public static void rollback(){
		getEntityManager().getTransaction().rollback();
	}
	
	public static Query createQuery(String query){
		return getEntityManager().createQuery(query);
	}
	
	public static void log(String info, Level level, Throwable ex){
		logger.log(level, info, ex);
	}
}
